import os
import re
import csv
import shutil
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[logging.FileHandler('simplified_dat_processor.log'), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

def extract_device_info(content):
    """从文件内容中提取品牌、型号和UID信息"""
    brand = None
    model = None
    uid = None
    
    # 提取品牌信息（支持带引号/不带引号，冒号/等号分隔）
    brand_match = re.search(r'ro\.product\.brand["\']?\s*[:=]\s*["\']?([^\s,}]+)', content)
    # 提取型号信息（同上）
    model_match = re.search(r'ro\.product\.model["\']?\s*[:=]\s*["\']?([^\s,}]+)', content)
    # 提取UID信息（支持通用UID格式）
    uid_match = re.search(r'uid["\']?\s*[:=]\s*["\']?([^\s,}]+)', content)
    
    if brand_match:
        brand = brand_match.group(1).strip('"\'')  # 移除可能的引号
    if model_match:
        model = model_match.group(1).strip('"\'')
    if uid_match:
        uid = uid_match.group(1).strip('"\'')
    
    return brand, model, uid  # 返回三个值

def collect_dat_files(root_dir="data_2"):
    """遍历目录收集所有DAT文件"""
    dat_files = []
    if not os.path.exists(root_dir):
        logger.warning(f"创建目录: {root_dir}")
        os.makedirs(root_dir, exist_ok=True)
    
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.lower().endswith('.dat'):
                dat_files.append(os.path.abspath(os.path.join(dirpath, filename)))
    
    logger.info(f"找到 {len(dat_files)} 个DAT文件")
    return dat_files

def parse_dat_file_simplified(file_path):
    """简化版DAT文件解析器（仅使用extract_device_info方法）"""
    result = {'brand': None, 'model': None, 'uid': None, 'file_path': file_path}
    
    # 尝试多种编码读取文件内容
    encodings = ['utf-8', 'gbk', 'latin-1']
    content = None
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()  # 读取完整内容
            break
        except Exception as e:
            continue  # 尝试下一种编码
    
    if content:
        # 直接使用老板提供的提取方法
        brand, model, uid = extract_device_info(content)
        result.update({'brand': brand, 'model': model, 'uid': uid})
    else:
        logger.warning(f"无法读取文件内容: {file_path}")
    
    return result

def generate_csv_report(parsed_results, csv_path="simplified_device_info.csv"):
    """生成简化版CSV报告"""
    with open(csv_path, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=['品牌', '型号', 'UID', '文件路径'])
        writer.writeheader()
        for item in parsed_results:
            writer.writerow({
                '品牌': item['brand'] or '',
                '型号': item['model'] or '',
                'UID': item['uid'] or '',
                '文件路径': item['file_path']
            })
    logger.info(f"CSV报告生成: {os.path.abspath(csv_path)}")

def create_brand_folders(brands, base_dir="."):
    """创建品牌文件夹和Unknown文件夹"""
    folder_info = {'unknown': os.path.join(base_dir, "Unknown"), 'brands': {}}
    os.makedirs(folder_info['unknown'], exist_ok=True)
    
    for brand in brands:
        if brand:
            sanitized = re.sub(r'[\\/:*?"<>|]', '_', brand).strip()[:50]
            folder = os.path.join(base_dir, sanitized)
            os.makedirs(folder, exist_ok=True)
            folder_info['brands'][brand] = folder
    
    return folder_info

def copy_files_to_folders(parsed_results, folder_info):
    """按品牌复制文件到对应文件夹"""
    stats = {'total': len(parsed_results), 'copied': 0, 'unknown': 0}
    
    for item in parsed_results:
        src = item['file_path']
        brand = item['brand']
        model = item['model']
        dst_folder = folder_info['brands'].get(brand) if (brand and model) else folder_info['unknown']
        
        if dst_folder:
            dst = os.path.join(dst_folder, os.path.basename(src))
            if not os.path.exists(dst):
                shutil.copy2(src, dst)
                stats['copied'] += 1
            else:
                logger.info(f"跳过已存在文件: {dst}")
        
        if not (brand and model):
            stats['unknown'] += 1
    
    return stats

def main():
    """简化版主流程"""
    logger.info("======= 简化版DAT文件处理器启动 =======")
    
    # 1. 收集文件
    dat_files = collect_dat_files()
    if not dat_files:
        logger.info("无DAT文件可处理，程序退出")
        return
    
    # 2. 解析文件（仅使用老板提供的extract_device_info方法）
    parsed_results = [parse_dat_file_simplified(fp) for fp in dat_files]
    
    # 3. 生成CSV
    generate_csv_report(parsed_results)
    
    # 4. 创建文件夹
    unique_brands = {item['brand'] for item in parsed_results if item['brand']}
    folder_info = create_brand_folders(unique_brands)
    
    # 5. 复制文件
    stats = copy_files_to_folders(parsed_results, folder_info)
    
    # 输出结果
    logger.info("\n======= 处理完成 =======")
    logger.info(f"总文件数: {stats['total']}")
    logger.info(f"成功分类: {stats['copied'] - stats['unknown']}")  # 排除特例文件
    logger.info(f"特例文件: {stats['unknown']}")
    logger.info(f"分类成功率: {(stats['copied'] - stats['unknown'])/stats['total']:.2%}")
    logger.info("=======================")
    
    set_result(
        status="success",
        message="简化版处理器完成",
        stats=stats,
        classification_rate=(stats['copied'] - stats['unknown'])/stats['total']
    )

if __name__ == "__main__":
    main()
